package common.test;

import common.ListNode;

/**
 * 19. 删除链表的倒数第 N 个结点
 */
public class _19_RemoveNthFromEnd {

    public ListNode removeNthFromEnd(ListNode head, int n) {
        if (head == null || n < 1) {
            return head;
        }

        ListNode ans = new ListNode(0, head);
        // 寻找倒数第N个结点的前一个
        ListNode pre = ans;
        ListNode tail = head;
        for (int i = 0; i < n; i++) {
            tail = tail.next;
        }
        while (tail != null) {
            pre = pre.next;
            tail = tail.next;
        }
        pre.next = pre.next.next;
        return ans.next;
    }
}
